﻿// Sequin.WebLogs.IO.GenericLogReader
//
// (c) 2011 Arthur Pitman
//
// Part of the Sequin Library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License (Version 2.1) as published by the Free Software Foundation.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License (Version 2.1) along with this library; if not, write to the 
// Free Software Foundation, Inc., 
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
// or see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace Sequin.WebLogs.IO
{
    /// <summary>
    /// Reads a generic log file
    /// Format: timestamp request_type request response_code referrer ip_address user_agent
    /// </summary>
    public class GenericLogReader : LogReader
    {
        /// <summary>
        /// Space splitter - elements are seperated by spaces
        /// </summary>
        protected static char[] spaceSplitter = new char[] { ' ' };

        /// <summary>
        /// Initializes a new <see cref="GenericLogReader"/> instance with file or files specified by path parameter
        /// </summary>
        /// <param name="path">The location of file or files</param>
        public GenericLogReader(string path)
            : base(path)
        {
        }

        /// <summary>
        /// Reads a <see cref="LogEntry"/>
        /// </summary>
        /// <returns>The <see cref="LogEntry"/> or null if none is available</returns>
        public override LogEntry ReadLogEntry()
        {
            // try to read a line
            string line = ReadLine();
            if (line == null)
                return null;

            // split the line into elements
            string[] elements = line.Split(spaceSplitter);

            // create a LogEntry
            return new LogEntry(                
                DateTime.Parse(elements[1]), 
                LogEntry.GetRequestType(elements[2]), 
                elements[3], 
                int.Parse(elements[4]), 
                elements[5],
                new UserIdentity(IPAddress.Parse(elements[0]), // IP
                    UserIdentity.MapUserAgentToId(elements[6]))); // user agent
        }
    }
}
